package com.assistant.config;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.assistant.util.JsonUtil;
import com.assistant.vo.resp.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Slf4j
@Configuration
public class SentinelExceptionHandlerImpl implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        StringBuffer url = request.getRequestURL();
        if ("GET".equals(request.getMethod()) && StringUtil.isNotBlank(request.getQueryString())) {
            url.append("?").append(request.getQueryString());
        }
        AjaxResult ajaxResult = null;
        if(e instanceof FlowException) {//限流异常
            ajaxResult = AjaxResult.error("您的访问过于频繁，请稍后重试");
        }else if (e instanceof DegradeException) {//降级异常
            ajaxResult = AjaxResult.error("调用服务响应异常,已进行降级");
        }else if (e instanceof ParamFlowException) {//热点参数异常
            ajaxResult = AjaxResult.error("您对热点参数访问过于频繁，请稍后重试");
        }else if (e instanceof SystemBlockException) {//系统保护规则
            ajaxResult = AjaxResult.error("已触碰系统的红线规则，请检查访问参数");
        }else if (e instanceof AuthorityException) {//授权规则
            ajaxResult = AjaxResult.error("授权规则检测不同，请检查访问参数");
        }else {//其他规则
            ajaxResult = AjaxResult.error("非法访问，请稍后重试");
        }
        String body = JsonUtil.toJson(ajaxResult);
        log.error("sentinel 报错拦截:{}",body);
        response.setStatus(500);
        response.setCharacterEncoding("utf-8");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        //springmvc的一个json转换类(jockson)
        PrintWriter out = response.getWriter();
        out.print(body);
        out.flush();
        out.close();
    }
}
